import { defineStore } from 'pinia'
import { LoginRegister, userMenu } from '@/api/login'
import type { UserInfoParams, UserInfoData } from '@/api/user'
import type { LoginPort } from '@/api/login'
import { ElMessage } from 'element-plus'
import { constantRoutes as staticRoutes, dynamicRoutes as allAsyncRoutes, anyRoute } from '@/router'
import router from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import cloneDeep from 'lodash/cloneDeep'
import JMessage from '@/utils/JMessage'
import request from '@/utils/JRequest'
import { i18n, Jzhcn } from '@/i18n/index'

// 动态注册路由
function addRoutes(routes: RouteRecordRaw[]) {
  routes.forEach((route) => {
    router.addRoute(route)
  })
}

// 清空路由
function resetRouter() {
  let routes = router.getRoutes()
  routes.forEach((item) => {
    if (item.name) {
      router.removeRoute(item.name)
    }
  })
  addRoutes(allAsyncRoutes)
}
// 字符串转换为对象
function strToArr(str: string) {
  let string = ''
  const arr = str.split('.')
  if (arr.length === 1) {
    string = Jzhcn[arr[0]]
  } else if (arr.length === 2) {
    string = Jzhcn[arr[0]][arr[1]]
  } else if (arr.length === 3) {
    string = Jzhcn[arr[0]][arr[1]][arr[2]]
  } else if (arr.length === 4) {
    string = Jzhcn[arr[0]][arr[1]][arr[2]][arr[3]]
  } else if (arr.length === 5) {
    string = Jzhcn[arr[0]][arr[1]][arr[2]][arr[3]][arr[4]]
  } else if (arr.length === 6) {
    string = Jzhcn[arr[0]][arr[1]][arr[2]][arr[3]][arr[4]][arr[5]]
  }
  return string
}
// 过滤路由
function filterAsyncRoutes(allAsyncRoutes: RouteRecordRaw[], routeNames: string[]) {
  const asyncRoutes = allAsyncRoutes.filter((item: any) => {
    if (item.meta && item.meta.title && item.meta.title.includes('menu') && routeNames.indexOf(strToArr(item.meta.title) as string) !== -1) {
      if (item.children && item.children.length) {
        item.children = filterAsyncRoutes(item.children, routeNames)
      }
      return true
    }
  })
  return asyncRoutes
}

interface tokeListData {
  token: string
  userInfo: any
  menuRoutes: RouteRecordRaw[]
}

export const useUserInfoStore = defineStore('userInfo', {
  state(): tokeListData {
    return {
      token: sessionStorage.getItem('Authorization') || '',

      userInfo: {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        name1: '',
        avatar: ''
      }, // 静态路由是否展示
      menuRoutes: []
    }
  },
  actions: {
    async login(userInfo: LoginPort) {
      const result = await LoginRegister(userInfo)
      if (result.code === 501) {
        ElMessage.error(result.message)
        return
      } else if (result.code === 502) {
        ElMessage.error('密码有误请检查')
        return
      } else if (result.code === 503) {
        ElMessage.error(result.message)
        return result
      } else if (result.code === 508) {
        ElMessage.error(result.message)
        return result
      } else if (result.code === 504) {
        ElMessage.error(result.message)
        return result
      } else {
        this.token = result.data.Authorization
        let userInfoList = JSON.stringify(result.data.userInfo)
        sessionStorage.setItem('companyId', result.data.companyId)
        sessionStorage.setItem('userInfo', userInfoList)
        sessionStorage.setItem('name', result.data.name)
        sessionStorage.setItem('Authorization', result.data.Authorization)
        JMessage.success('登录成功')
        router.push('/index')
        return 'ok'
      }
    },

    // 获取用户信息
    async getInfo() {
      try {
        // const res = await request.get(`/system/menu/getSystems?systemId=${1}`)
        // console.log(res)
        const result = await userMenu()
        let UserRoterTitle = result.data.map((item: any) => {
          return item.chiName
        })
        this.userInfo.name1 = sessionStorage.getItem('name')
        if (sessionStorage.getItem('menuRoutes')) {
          this.menuRoutes = JSON.parse(sessionStorage.getItem('menuRoutes') as string)
        } else {
          const routes = (await filterAsyncRoutes(cloneDeep(staticRoutes), UserRoterTitle)) as any
          console.log(staticRoutes)

          this.menuRoutes = routes.concat(anyRoute)
          sessionStorage.setItem('menuRoutes', JSON.stringify(this.menuRoutes))
        }
      } catch (error) {
        // 如果失败了 就返回一个失败的promise
        return Promise.reject(error)
      }
    },

    async reset() {
      this.token = ''
      this.userInfo = {}
      sessionStorage.removeItem('Authorization')
      sessionStorage.removeItem('menuRoutes')
    },

    async logout() {
      try {
        this.reset()
        resetRouter()
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    }
  }
})
